package jn.chen.utils.emailCode.service.impl;

import jn.chen.utils.emailCode.bean.JavaBean;
import jn.chen.utils.emailCode.dto.EmailDTO;
import jn.chen.utils.emailCode.service.SendEmail;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.Arrays;
import java.util.Date;

/**
 * @className: SendEmailImpl
 * @author: chenLin
 * @version: 1.0.0
 * @description:
 * @date: 2022/11/1 0001 14:47
 */
@Service
public class SendEmailImpl implements SendEmail {

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private TemplateEngine templateEngine;

    @Autowired
    private JavaBean javaBean;

    @Autowired
    private Environment environment;


    @Override
    public String sendHtmlEmail(EmailDTO email) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        // 邮件的标题
        helper.setSubject(javaBean.getFromName());
        // 发送者
        helper.setFrom(javaBean.getUsername());
        // 接受者
        helper.setTo(email.getTo());
        // 时间
        helper.setSentDate(new Date());

        // 这里引入的是Template的Context
        Context context = new Context();
        //设置模板中的变量
        context.setVariable("verifyCode", Arrays.asList("内容?????"));
        // 第一个参数为模板的名称
        String process = templateEngine.process("email.html", context);
        // 第二个参数true表示这是一个html文本
        helper.setText(process, true);
        mailSender.send(mimeMessage);
        return "发送成功！";
    }
}
